<!DOCTYPE html>
<html>
<head>
<title>Virtual Stock Market</title>

<link rel="stylesheet" type="text/css" href="/css" />
<script type="text/javascript" src="/knockout"></script>
<script type="text/javascript" src="/jquery"></script>
<script type="text/javascript" src="/nowjs/now.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	// Default room
	var theroom = 'main';
	
	// When the server sends a message
	now.receiveMessage = function(name, message) {
		$("#messages").append("<br><b>" + name + "</b>: " + message);
	};

	// On message
	$("#text-input").keypress(function(e) {
		if(e.keyCode == 13) {
			if($("#text-input").val() == '') {
				setStatus('Enter some chat message!');
			}
			else {
				now.distributeMessage($("#text-input").val(),theroom);
				$("#text-input").val("");
			}
		}
	});
	
	/*
		MAIN VIEW MODEL
	*/
  
	function playerViewModel() {
		var self = this;
		
		self.username = ko.observable("");
		self.credit = ko.observable(1000);
		self.userArray = ko.observableArray([]);
		
		self.allCompanies = ko.observableArray([]);
		
		self.myStocks = ko.observableArray([]);
		
		self.winners = ko.observableArray([]);
		
		// User buys stock
		self.buyStock = function(stock) {
			var stockAmount = parseInt($("#stockAmount").val());
		
			if(self.credit() - (stockAmount * stock.stockPrice) < 0) {
				setStatus('You don\'t have enough credits!');
			}
			else {
				var found = false;
				for(var i = 0; i < self.myStocks().length; i++) {
					if(self.myStocks()[i].companyID == stock.id) {
						found = true;
						var newstockAmount = self.myStocks()[i].stockAmount + stockAmount;
						self.myStocks.replace(self.myStocks()[i], new stockVM(stock.name, stock.id, stock.stockPrice, newstockAmount));
					}
				}
			
				if(!found) {
					self.myStocks.push(new stockVM(stock.name, stock.id, stock.stockPrice, stockAmount));
				}
				
				// Get the new stock price
				var boughtStocks;
				now.getStockPriceByCompanyID(stock.id, function(price) {
					boughtStocks = price * stockAmount;
					setStatus('You bought ' + stockAmount + ' stocks from ' + stock.name + ' for $' + boughtStocks);
					self.credit(self.credit() - boughtStocks);
				});
				
				now.updateStockPrice(stock.id, stockAmount, true);
			}
		};
		
		// User sells stock
		self.sellStock = function(stock) {
			var stockAmount = parseInt($("#stockAmount").val());
		
			for(var i = 0; i < self.myStocks().length; i++) {
				if(self.myStocks()[i].companyID == stock.companyID) {
					if(stockAmount > self.myStocks()[i].stockAmount) {
						stockAmount = self.myStocks()[i].stockAmount;
					}
					var newstockAmount = self.myStocks()[i].stockAmount - stockAmount;
					if(newstockAmount <= 0) {
						self.myStocks.remove(self.myStocks()[i]);
					}
					else {
						self.myStocks.replace(self.myStocks()[i], new stockVM(stock.companyName, stock.companyID, stock.stockPrice, newstockAmount));
					}
				}
			}
			
			// Get the new stock price
			var soldStocks;
			now.getStockPriceByCompanyID(stock.companyID, function(price) {
				soldStocks = price * stockAmount;
				setStatus('You sold ' + stockAmount + ' stocks from ' + stock.companyName + ' for $' + soldStocks);
				self.credit(self.credit() + soldStocks);
			});
			
			now.updateStockPrice(stock.companyID, stockAmount, false);
		};
		
		// User changes a room (private chat)
		self.changeRoom = function(elem) {
			if(elem.name == self.username) {
				setStatus('What, are you gonna chat with yourself?');
			}
			else {
				if(theroom == elem.name) {
					theroom = 'main';
					$('.user_' + elem.name).removeClass('selectedUser');
				}
				else {
					theroom = elem.name;
					$("[class^=user_]").removeClass('selectedUser');
					$('.user_' + elem.name).addClass('selectedUser');
				}
				
				setStatus('You are now chatting with ' + theroom);
			}
		};
	}
	
	/*
		EXTRA VIEW MODELS
	*/
	
	// User ViewModel
	function userVM(name) {
		var self = this;
		self.name = name;
	}
	
	// Company ViewModel
	function companyVM(id, name, stocks, stockPrice, raisedPrice) {
		var self = this;
		self.id = id;
		self.name = name;
		self.stocks = stocks;
		self.stockPrice = stockPrice;
		self.raisedPrice = raisedPrice;
	}
	
	// Stock ViewModel
	function stockVM(companyName, companyID, stockPrice, stockAmount) {
		var self = this;
		self.companyName = companyName;
		self.companyID = companyID;
		self.stockPrice = stockPrice;
		self.stockAmount = stockAmount;
	}
	
	// Player ViewModel
	function playerVM(username, credit) {
		var self = this;
		self.username = username;
		self.credit = credit;
	}
	
	// Initiate main ViewModel
	var pvm = new playerViewModel();
	// Ask the user for name
	pvm.username = now.name = prompt("What is your name?");
	
	// Repopulate connected users
	now.repopulateUsers = function(allusers) {
		pvm.userArray.removeAll();
		for(var i = 0; i < allusers.length; i++) {
			pvm.userArray.push(new userVM(allusers[i]));
		}
	};
	
	// Update the timer
	now.updateTimer = function(newTime) {
		$("#timeLeft").html(formatTime(newTime));
		if(newTime == 0) {
			$("#timeLeft").html('-');
			var stats = new playerVM($("#username").html(), pvm.credit());
			now.sendStatistics(stats);
		}
	};
	
	// Display winner / no game in progress
	now.showScoreboard = function(winnerArr) {
		pvm.winners.removeAll();
		for(var i = 0; i < winnerArr.length; i++) {
			pvm.winners.push(winnerArr[i]);
		}
		
		$('html body *').hide();
		$('#scoreboard').show();
		$('#scoreboard').find('*').each(function() { $(this).show(); });
	};
	
	// Format seconds: HH:MM:SS
	function formatTime(secs)
	{
		var hours = Math.floor(secs / 3600);
		var remainder = Math.floor(secs % 3600);
		var minutes = Math.floor(remainder / 60);
		var seconds = Math.floor(remainder % 60);

		return ( (hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":" + (seconds < 10 ? "0" : "") + seconds );
	}
	
	// Repopulate company stock
	now.repopulateCompanies = function(companyArray) {
		pvm.allCompanies.removeAll();
		for(var i = 0; i < companyArray.length; i++) {
			pvm.allCompanies.push(new companyVM(companyArray[i].id, companyArray[i].name, companyArray[i].stocks, companyArray[i].stockPrice, companyArray[i].raisedPrice));
		}
	};
	
	// Rename user's nickname
	$("#username").click(function() {
		var newName = prompt("What is your NEW name?");
		now.changeName(newName);
		
		now.name = newName;
		pvm.username = newName;
		$("#username").html(newName);
	});
	
	// Stock range slider
	$("#stockAmount").change(function() {
		$("#stockAmountText").html($("#stockAmount").val());
	});
	
	// Set status message
	function setStatus(msg) {
		$("#status").html(msg).hide().fadeIn(1500);
	}
	
	ko.applyBindings(pvm);
});
</script>
</head>

<body>
<div id="scoreboard">
	<h1>GAME OVER!</h1>
	<p>Scoreboard:</p>
	<table cellpadding="0" cellspacing="0" border="1" align="center">
		<thead>
			<tr>
				<th width="100">Name</th>
				<th width="100">Score</th>
			</tr>
		</thead>
	
		<tbody data-bind="foreach: winners">
			<tr>
				<td><span data-bind="text: username"></span></td>
				<td><span data-bind="text: credit"></span></td>
			</tr>
		</tbody>
	</table>
</div>

<div id="playerinfo">
	<b>Username:</b> <span id="username" data-bind="text: username"></span> |
	<b>Credit:</b> $<span id="credit" data-bind="text: credit"></span> |
	<b>Time left:</b> <span id="timeLeft">-</span>
	<div>&nbsp;<span id="status">&nbsp;</span></div>
</div>

<div id="wrapper">
	<marquee id="stockScroll" data-bind="foreach: allCompanies">
		<img data-bind="attr: { src: raisedPrice ? 'green' : 'red' }" />
		<span data-bind="text: name"></span>
		$<span data-bind="text: stockPrice"></span>
		<b>//</b>
	</marquee>

	<div id="myStocks">
		<h1>My Stocks</h1>
		<div data-bind="visible: myStocks().length <= 0">
			You don't own any stocks!
		</div>
		<div class="companies" data-bind="foreach: myStocks">
			<div class="company">
				<p><span class="companyName" data-bind="text: companyName"></span> (<span class="companyStocks" data-bind="text: stockAmount"></span>)</p>
				<button data-bind="click: $parent.sellStock">SELL</button>
			</div>
		</div>
	</div>
	
	<div id="stockMarket">
	
		<div style="float:right;padding:10px"><b>Amount:</b> <span id="stockAmountText">10</span><br /><input id="stockAmount" type="range" min="1" max="100" value="10" /></div>
	
		<div id="allStocks">
			<h1>Stock Market</h1>
			<div data-bind="visible: allCompanies().length <= 0">
				There are no stocks on the market!
			</div>
			<div class="companies" data-bind="foreach: allCompanies">
				<div class="company">
					<p class="companyName"><img style="width:15px" data-bind="attr: { src: raisedPrice ? 'green' : 'red' }" /> <span data-bind="text: name"></span> $<span class="companyStockPrice" data-bind="text: stockPrice"></span></p>
					<p>(<span class="companyStocks" data-bind="text: stocks"></span>)</p>
					<button data-bind="click: $parent.buyStock">BUY</button>
				</div>
			</div>
		</div>
	</div>

	<div id="chat">
		<h1>Chat</h1>
		<p><b>Connected users:</b>
		<ul data-bind="foreach: userArray">
			<li data-bind="click: $parent.changeRoom, text: name, attr: { class : 'user_' + $data.name }"></li>
		</ul>
		</p>
		<input type="text" id="text-input">
		<div id="messages"></div>
	</div>
</div>
</body>
</html>